package com.record.aspct;

import com.record.service.ForbiddentService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;

@Aspect
@Component
public class AllowWordAspect {
    @Autowired
    private ForbiddentService forbiddentService;

    @Pointcut("@annotation(com.record.annotation.AllowWord)")
    public void allowWordPointcut() {

     }

     // 1.方法执行前  2. 方法执行后 3.环绕通知
     @Before("allowWordPointcut()")
     public void checkAllowWord(JoinPoint joinPoint) {
         Object[] args = joinPoint.getArgs();
         for (Object arg : args) {
             checkForbiddenWord(arg);
         }
     }

     private void checkForbiddenWord(Object entity) {
          if(entity == null){
              return;
          }

         Field[] fields = entity.getClass().getDeclaredFields();
         for (Field field : fields) {
             if(field.getType().equals(String.class)){
                 field.setAccessible(true); //给权限  去访问
                 try{
                     String value = (String)field.get(entity); //强转 null
                     System.out.println("当前被校验的参数为:" + value);
                     if(!StringUtils.isEmpty(value)){
                         if(forbiddentService.isForbidden(value)){
                             throw  new RuntimeException("存在违禁词");
                         }
                     }
                 }catch (IllegalAccessException e){
                     System.out.println("出现异常: "+e.getMessage());
                 }
             }
         }
     }
}
